//
//  AcountModel.m
//  SinaWeibo
//
//  Created by Apple on 16/8/13.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "AcountModel.h"
#import <objc/runtime.h>


#define kAcountModel @"acountModel.plist"


@implementation AcountModel

-(instancetype)initWithDict:(NSDictionary *)dict{
    if (self == [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+(instancetype)acountModelWithDict:(NSDictionary *)dict{
    
    return [[self alloc]initWithDict:dict];
    
}


-(BOOL)saveModel{
    // 1.获取沙河路径
    NSString *accountPath = [kAcountModel appendToDocument];
    
    // 2.生成真正的过期时间
    NSDate *now = [NSDate date];
    self.expires_time = [now dateByAddingTimeInterval:[self.expires_in doubleValue]];
    
    
    // 2.将自己存储起来
    return [NSKeyedArchiver archiveRootObject:self toFile:accountPath];
    
}

//返回一个从沙盒保存的acount对象
+(instancetype)acountModelFromSandbox{
    
    AcountModel *instance;
    
    //1.获取acount保存的路径
    NSString *acountPath = [kAcountModel appendToDocument];
    
    //2.解归档
    instance = [NSKeyedUnarchiver unarchiveObjectWithFile:acountPath];
    
    // 3.判断授权是否过期
    NSDate *now = [NSDate date];
    // 2014-2-1    2020-1-31
    if ([now compare:instance.expires_time] != NSOrderedAscending) {
        
        
        return nil;
    }
    
    //3.返回届归档出来的对象
    return instance;
}




#pragma mark - NSCoding

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    unsigned int outCount;
    
    //取出所有对象
    objc_property_t *property = class_copyPropertyList([self class], &outCount);
    
    for (int i = 0; i<outCount; i++) {
        //遍历获得所有属性名称
        const char *propertyName = property_getName(property[i]);
        
        //将属性名称转化为字符串
        NSString *name = [NSString stringWithUTF8String:propertyName];
        
        //用kvc获取对应属性的值
        id value = [self valueForKey:name];
        
        //归档
        [aCoder encodeObject:value forKey:name];

    }
    
}



- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    if (self == [super init]) {
        unsigned int outCount = 0 ;
        //取出所有对象
        objc_property_t *property = class_copyPropertyList([self class], &outCount);
        
        //遍历所有对象
        for (int i = 0 ; i<outCount; i++) {
            const char *propertyName = property_getName(property[i]);
            
            NSString *name = [NSString stringWithUTF8String:propertyName];
            
            //解归档当前文档的值
            id value = [aDecoder decodeObjectForKey:name];
            
            //设置当前属性的值
            [self setValue:value forKey:name];
            
        }
        
    }
    return self;

}

@end
